import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_app_custom_chat/chart/utils/ex.dart';
import 'package:flutter_app_custom_chat/chart/utils/monotonex.dart';

///折线图
class LineChartPaint extends CustomPaint {
  final double width;
  final double height;
  final List<double> data;
  final double maxY;
  final double padding;
  final double indexWidth;
  final bool isSmooth;

  LineChartPaint(this.width, this.height, this.data, this.maxY, this.padding,
      this.indexWidth,
      {this.isSmooth = true});

  @override
  Size get size => Size((1 + data.length) * indexWidth, height);

  @override
  CustomPainter get painter =>
      LineChartPainter(data, maxY, padding, indexWidth, isSmooth);
}

class LineChartPainter extends CustomPainter {
  final List<double> data;
  final double maxY;
  final double padding;
  final double indexWidth;
  final bool isSmooth;

  LineChartPainter(
      this.data, this.maxY, this.padding, this.indexWidth, this.isSmooth);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.blue
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    var point = Offset(padding, size.height - padding);
    var topPoint = Offset(padding, padding);
    List<Offset> points = [];
    for (int i = 1; i <= data.length; i++) {
      var offset =
          change(point, topPoint, indexWidth, padding, i, maxY, data);
      points.add(offset);
    }
    if (isSmooth) {
      _drawSmoothLine(canvas, paint, points);
    } else {
      canvas.drawPoints(PointMode.polygon, points, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

void _drawSmoothLine(Canvas canvas, Paint paint, List<Offset> points) {
  final path = new Path()
    ..moveTo(points.first.dx.toDouble(), points.first.dy.toDouble());
  MonotoneX.addCurve(path, points);
  canvas.drawPath(path, paint);
}
